package com.homelink.android.explorerup.component;

import java.io.File;

import android.os.AsyncTask;
import android.util.Log;

import com.homelink.android.explorerup.R;
import com.homelink.android.explorerup.adapter.BaseFileListAdapter;
import com.homelink.android.explorerup.view.NumOfImageView;
import com.homelink.android.util.FileTypes;

public class ObtainFilePropertiesTask extends
		AsyncTask<BaseFileListAdapter.ViewHolder, Integer, Integer> {
	public static final String TAG = "ObtainFilePropertiesTask";
	private BaseFileListAdapter.ViewHolder mViewHolder;
	private String mPath;
	private OnObtainFilePropertiesListener mListener;

	public ObtainFilePropertiesTask(String basePath) {

		mPath = basePath;
	}

	public void setListener(OnObtainFilePropertiesListener l) {
		mListener = l;
	}

	@Override
	protected Integer doInBackground(BaseFileListAdapter.ViewHolder... params) {
		mViewHolder = params[0];
		File file = new File(mPath + "/" + mViewHolder.nameTxt);
		// Log.d(TAG, mPath + "" + params[0]) ;

		// Log.d(TAG,String.valueOf(subFiles) + params[0].nameTxt);
		boolean isFolder = file.isDirectory();
		params[0].isFolder = isFolder;
		int resId = getIcon(mViewHolder.nameTxt, isFolder);
		if (isFolder) {
			String[] subFiles = file.list();
			publishProgress(resId, (subFiles == null) ? 0 : subFiles.length);

		} else {
			publishProgress(resId, -1);
		}

		return null;
	}

	/**
	 * -1 if file
	 */
	@Override
	protected void onProgressUpdate(Integer... values) {
		/**
		 * if number is -1, don't need to draw
		 */
		((NumOfImageView) mViewHolder.iconImage).setNumber(values[1]);
		mViewHolder.iconImage.setImageResource(values[0]);
		if (values[0] == R.drawable.file_96) {
			Log.d(TAG, "unknwo file type : " + mViewHolder.nameTxt);
			mViewHolder.iconImage.setIsUnkownType(true);
		}
		if (mViewHolder.nameTxt != null) {
			int index = mViewHolder.nameTxt.lastIndexOf(".");
			if (index > 0) {
				mViewHolder.iconImage.setSuffix(mViewHolder.nameTxt.substring(
						index+1, mViewHolder.nameTxt.length()));
			}
		}

		if (mListener != null) {
			mListener.onObtainFinished(mViewHolder);
		}
	}

	private int getIcon(String fileName, boolean isDir) {
		if (isDir) {
			return R.drawable.folder_96;
		} else {
			return FileTypes.getIcon(fileName);
		}
	}

	public static interface OnObtainFilePropertiesListener {
		public void onObtainFinished(BaseFileListAdapter.ViewHolder holder);
	}

}
